package com.lebang.controller.api;

import com.lebang.aop.Sessionid;
import com.lebang.common.MemberLock;
import com.lebang.common.Require;
import com.lebang.common.util.RequestUtil;
import com.lebang.common.validcode.ValidCodeStatus;
import com.lebang.common.validcode.ValidCodeUtil;
import com.lebang.component.RedisClient;
import com.lebang.domain.LogoutRecord;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.member.LbbMember;
import com.lebang.model.ResultModel;
import com.lebang.model.ValidCodeRecord;
import com.lebang.model.enums.buss.UserStatus;
import com.lebang.service.LogoutService;
import com.lebang.service.MemberWalletService;
import com.lebang.service.buss.MemberService;
import com.lebang.service.buss.MemberTradeService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.common.UUIDUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.lebang.common.validcode.RedisLock.LOCKPHONECODE;

/**
 * @Author: xwj
 * @Date: 2019/10/28 10:27
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/logout")
public class LogoutApi {
    @Autowired
    private MemberService memberService;

    @Autowired
    private LogoutService logoutService;

    @Autowired
    private MemberWalletService memberWalletService;

    @Autowired
    private RedisClient redisClient;
    @Autowired
    private ValidCodeUtil validCodeUtil;

    @Autowired
    private MemberTradeService memberTradeService;



    /**
     * 返回审核记录
     */
    @Require
    @PostMapping("/record")
    @Sessionid
    public JsonData record(HttpServletRequest request){
        RequestHeaders requsetHeader = RequestUtil.getHeader(request);
        return Callback.success("success", "返回成功", logoutService.selectRecord(requsetHeader.getUserid(),null));

    }



    /**
     * 设备号不一致发送验证码校验
     */
    @Require
    @PostMapping("/validcode")
    @Sessionid
    public JsonData validCode(HttpServletRequest request){
        RequestHeaders requsetHeader = RequestUtil.getHeader(request);


        try {
            LbbMember member = memberService.selectMemberById(requsetHeader.getUserid());
            String phone = member.getPhone();
            if (!TextUtil.isMobile(phone)) {
                return Callback.fail("invalid_phone", "请输入正确的手机号！");
            }
            //加锁防止重复发
            String uuid = UUIDUtil.M();
            boolean a = redisClient.tryGetDistributedLock(LOCKPHONECODE.getName() + phone, uuid, 3000);
            if (a) {
                ValidCodeStatus validCode = validCodeUtil.getLogoutValidCode(phone,new ValidCodeRecord(request));
                if (validCode.isStatus()) {
                    //验证码存入redis中
                    redisClient.setex("loggout:send:record:"+phone, 300, validCode.getCode());
                    return Callback.success("success", "发送成功", "");
                } else {
                    return Callback.fail("fail", "发送失败" + validCode.getMsg(), null);
                }
            } else {
                return Callback.fail("fail", "请勿重复操作哦", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("error", e.getMessage());
        }
    }


    /**
     * 申请注销验证接口 （第一步）
     *
     */
    @Require
    @PostMapping("/valid")
    @Sessionid
    public JsonData valid(HttpServletRequest request,@RequestParam(value="code",required = false)String code) {
        //提取头部数据
        RequestHeaders requsetHeader = RequestUtil.getHeader(request);
        LbbMember member = memberService.selectMemberById(requsetHeader.getUserid());
        if (member == null) {
            return Callback.fail("202", "用户不存在");
        }

        List<ResultModel> list = logoutService.checkAcount(member, requsetHeader);
        if(TextUtil.isEmpty(code)){
            if (list.size()>0) {
                return Callback.fail("203", "异常",list);
            }
        }else{
            if(redisClient.get("loggout:send:record:"+member.getPhone())==null){
                return Callback.fail("204", "验证码过期");
            }
            if(!redisClient.get("loggout:send:record:"+member.getPhone()).equals(code)){
                return Callback.fail("205", "验证错误");
            }
        }

        boolean isThree = logoutService.checkCount(member, requsetHeader);

        if(isThree){
            return Callback.fail("206", "本月注销次数过多");
        }



        return Callback.success("200", "验证通过");
    }


    /**
     * 申请注销接口 (第二步)
     */
    @Require
    @Sessionid
    @PostMapping("/logout")
    @MemberLock
    public JsonData logout(HttpServletRequest request
            , @RequestParam(value = "msg") String msg
            , @RequestParam(value = "pictureOne") String pictureOne
            , @RequestParam(value = "pictureTwo") String pictureTwo) {
        //提取头部数据
        RequestHeaders requsetHeader = RequestUtil.getHeader(request);
        try {
            LogoutRecord logoutRecord = logoutService.selectRecord(requsetHeader.getUserid(),0);
            if(logoutRecord!=null){
                return Callback.fail("205", "请勿重复操作");
            }

            LbbMember member = memberService.selectMemberById(requsetHeader.getUserid());
            if (member == null) {
                return Callback.fail("201", "用户不存在");
            }
            long money = memberWalletService.getMoneyByMemberId(member.getMemberId());
            long allMoney = memberWalletService.getAllMoneyByMemberId(member.getMemberId());
            LogoutRecord record = logoutService.insertRecord(member, requsetHeader, money, allMoney, msg, pictureOne, pictureTwo);

             //将所有的待审核以及提现审核都拒绝
              logoutService.refuseAll(member, requsetHeader);
            return Callback.success("200", "申请成功",record );
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("205", "请勿重复操作");
        }
    }

    /**
     * 确定注销接口 （第三步）
     */
    @Require
    @Sessionid
    @PostMapping("/sure")
    public JsonData sure(HttpServletRequest request, @RequestParam(value = "id") Integer id) {
        //提取头部数据
        RequestHeaders requsetHeader = RequestUtil.getHeader(request);
        LbbMember member = memberService.selectMemberById(requsetHeader.getUserid());
        if (member == null) {
            return Callback.fail("201", "用户不存在");
        }
        if(!member.getStatus().equals(UserStatus.WaitCheck.name())){
            return Callback.fail("202", "用户不是待审核状态");
        }
        LogoutRecord record = logoutService.getRecord(id);
        if(record==null){
            return Callback.fail("203", "记录不存在");
        }
        if(!record.getMemberId().equals(requsetHeader.getUserid())){
            return Callback.fail("204", "用户不存在");
        }
        if(!record.getStatus().equals(2)){
            return Callback.fail("205", "审核结果未通过");
        }

        logoutService.sureOpera(requsetHeader,member,record);

        return Callback.success("200", "注销成功");

    }

    /**
     * 注销找回接口 (第三步)
     */
    @Require
    @Sessionid
    @PostMapping("/back")
    public JsonData back(HttpServletRequest request, @RequestParam(value = "id") Integer id) {
        //提取头部数据
        RequestHeaders requsetHeader = RequestUtil.getHeader(request);
        LbbMember member = memberService.selectMemberById(requsetHeader.getUserid());
        if (member == null) {
            return Callback.fail("201", "用户不存在");
        }
        if(!member.getStatus().equals(UserStatus.WaitCheck.name())){
            return Callback.fail("202", "用户不是待审核状态");
        }
        LogoutRecord record = logoutService.getRecord(id);
        if(record==null){
            return Callback.fail("203", "记录不存在");
        }
        if(!record.getMemberId().equals(requsetHeader.getUserid())){
            return Callback.fail("204", "用户不存在");
        }

        logoutService.backOpera(requsetHeader,member,record);
        return Callback.success("200", "找回成功");

    }


}
